package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.entity.user.PointInfo;
import com.qf.entity.user.User;
import com.qf.mapper.PointInfoMapper;
import com.qf.mapper.UserMapper;
import com.qf.service.PointInfoService;
import com.qf.service.PointTypeService;
import com.qf.util.TokenUtils;
import com.qf.util.UserUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * --- 万物归集  不随你我 ---
 * <p>
 * 快捷短语
 * main ==  public static void main(String[] args);
 * sout ==  System.out.println();
 *
 * @author shuhan
 * @date 2025/6/10
 * @desc
 */
@Service
public class PointInfoServiceImpl implements PointInfoService {

    @Resource
    private PointInfoMapper pointInfoMapper;

    @Resource
    private PointTypeService pointTypeService;

    @Resource
    private UserMapper userMapper;

    @Override
    public void add(Integer pointType) {
        // 防止重复签到,根据今日日期查找数据库中是否有记录
        Integer uid = TokenUtils.getUidFromToken();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 创建查询条件
        QueryWrapper<PointInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", uid)
                .ge("last_time", dateFormat.format(new Date()) + " 00:00:00") // 今天开始时间
                .lt("last_time", dateFormat.format(new Date()) + " 23:59:59"); // 今天结束时间

        // 执行查询
        PointInfo one = pointInfoMapper.selectOne(queryWrapper);

        if (one != null) {
            throw new RuntimeException("今日已签到");
        }

        // 添加签到记录
        PointInfo pointInfo = new PointInfo();
        Integer point = pointTypeService.findPointByPointType(pointType);
        pointInfo.setUid(uid);
        pointInfo.setPointType(pointType);
        pointInfo.setPoint(point);
        pointInfo.setLastTime(new Date());
        pointInfoMapper.insert(pointInfo);
        // 更新用户积分
        User user = new User();
        user.setId(uid);
        Integer oldPoint = findPointByUid(uid);
        user.setPoint(point+oldPoint);
        userMapper.updateById(user);

    }

    // 查询用户当前积分
    public Integer findPointByUid(Integer uid) {
        User user = userMapper.selectById(uid);
        return user.getPoint();
    }
}
